package cn.icatw.wallpaperapi.config;

import cn.icatw.wallpaperapi.handler.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @author icatw
 * @date 2022/3/2
 * @apiNote
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    //需要拦截的路径
    private final List<String> strings = Arrays.asList(
            "/api/collect/**",
            "/api/image/download/**",
            "/api/user/getCurrentUserInfo",
            "/api/user/updateUserAvatar",
            "/api/user/updateUserInfo",
            "/api/user/updateUserPass");
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //跨域配置，不可设置为*，不安全, 前后端分离项目，可能域名不一致
        //本地测试 端口不一致 也算跨域
        registry.addMapping("/**")
                //.allowedOrigins("http://localhost:8080")
                //.allowedOrigins("http://120.27.250.235:8080","http://120.27.250.235:80")
                .allowedOriginPatterns("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截test接口，后续实际遇到需要拦截的接口时，再配置为真正地拦截接口
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns(strings);
                //.addPathPatterns("/api/image/download/*")
                //.addPathPatterns("/api/collect/*");
        //.excludePathPatterns("/api/image");
        //.excludePathPatterns("/api/")
        //.addPathPatterns("/api/image/download")
        //.addPathPatterns("/api/collect/*")
        //.addPathPatterns("/articles/publish");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
